package com.zhongmai.yzfgrabanorder.netty_lib.netty;


import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * Created by 张俨 on 2017/10/9.
 */

public class NettyClientInitializer extends ChannelInitializer<SocketChannel> {

    private NettyListener listener;

    public NettyClientInitializer(NettyListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener == null ");
        }
        this.listener = listener;
    }

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        //netty是基于http的，所以要添加http编码器
        //        pipeline.addLast(new HttpClientCodec());
        //对写大数据流的支持
        //        pipeline.addLast(new ChunkedWriteHandler());
        //设置单次请求的文件大小上限
        //        pipeline.addLast(new HttpObjectAggregator(1024*1024));


        ChannelPipeline pipeline = ch.pipeline();
        //pipeline.addLast(new LoggingHandler(LogLevel.INFO));    // 开启日志，可以设置日志等级
        // 以("\n")为结尾分割的 解码器
        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
        pipeline.addLast(new IdleStateHandler(0, 20, 0));
        // 字符串解码 和 编码
        pipeline.addLast("decoder", new StringDecoder());  //接收解码方式
        pipeline.addLast("encoder", new StringEncoder()); //发送编码方式
        // 自己的逻辑Handler
        pipeline.addLast(new NettyClientHandler(listener));//处理数据接收
    }
}